package com.yungu.swift.api.base.handler;

import com.yungu.swift.api.base.gateway.GatewayHeader;
import com.yungu.swift.api.config.ApplicationConfig;
import com.yungu.swift.api.route.v2.passenger.PasLoginApi;
import com.yungu.swift.api.utils.RsaUtil;
import com.yungu.swift.autoconfig.redis.RedisStringCacheService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

import static com.yungu.swift.api.base.ApiErrorEnum.LOGIN_TOKEN_INVALID;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;

/**
 * @author : cuixiuyin
 * @date : 2019/10/28
 */
public class TokenHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String accessToken = request.getHeader(GatewayHeader.accessToken);
        RedisStringCacheService stringCacheService = SpringContextHolder.getBean(RedisStringCacheService.class);
        // 校验 token 是否存在
        String rid = request.getHeader(GatewayHeader.rid);
        String prefix = Objects.equals(rid, CommonConstant.PASSENGER + "") ? PasLoginApi.ACCESS_TOKEN_PREFFIX : "DRIVER_ACCESS_TOKEN_";
        if (StringUtils.isEmpty(stringCacheService.get(prefix + accessToken, false))) {
            response.setStatus(UNAUTHORIZED.value());
            outPrint(out, JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(LOGIN_TOKEN_INVALID.getCode(), LOGIN_TOKEN_INVALID.getMsg())));
            return false;
        }
        response.reset();
        return super.preHandle(request, response, handler);
    }


    private void outPrint(PrintWriter out, String jsonstr) {
        if (ApplicationConfig.SERVER_CONFIG.getSafety().getEncrypt()) {
            out.print(RsaUtil.doUrlAndEncrypt(jsonstr));
        } else {
            out.print(jsonstr);
        }
    }
}
